import axios from "axios";
import {showFailToast} from "vant";
import router from '../router'

export function request(config) {
	const instance = axios.create({
		baseURL: 'https://api.shop.eduwork.cn',
		timeout: 5000
	})
	// 请求拦截
	instance.interceptors.request.use(config => {
		// 获取Token
		const token = window.localStorage.getItem('token');
		// 如果获取到了token，则给所有请求添加上此token
		if (token) {
			config.headers.Authorization = `Bearer ${token}`
		}
		return config;
	}, err => {
		return err
	})
	// 响应拦截
	instance.interceptors.response.use(res => {
		return res.data ? res.data : res;
	}, err => {
		// 如果没有授权则跳转到登录页面
		if (err.response.status === 401) {
			showFailToast('请先登录');
			router.push({path: '/login'})
		}
	})
	return instance(config);
}